import { instantiate, Prefab, Tween } from 'cc';
import { _decorator, Component, Node, Label, tween, view, UITransform, Vec3, SpriteAtlas, SpriteFrame, Sprite, Button, ScrollView, find, math, RichText, EventTouch, WebView } from 'cc';
import { App } from '../../App';
import { EventConst } from '../../common/Common';
import CommConst from '../../const/CommConst';
import wsTool from '../../net/ws';
import { PD } from '../../player/PlayerData';
import { loadCommonPreFab, setLanguagePopuUp, showErrorTip, showTip, showTipBox } from '../../tools/PopuUp';
import UtilTool from '../../tools/UtilTool';
import AbstractComponent from '../../base/AbstractComponent';
import { BeMasterWnd } from './../multiplay/BeMasterWnd';
import { LabelOutline } from 'cc';
import { MineCuePanel } from './MineCuePanel';
import { UpgradeCuePanel } from './UpgradeCuePanel';
const { ccclass, property } = _decorator;

// 我的界面
@ccclass('MinePanel')
export class MinePanel extends AbstractComponent {

    @property(Button)
    btn_become_master: Button = null; // 成为球室持有人按钮

    @property(Button)
    btn_income: Button = null; // 收益明细按钮

    @property(Label)
    label_nick : Label = null; // 昵称

    @property(Label)
    label_address : Label = null; // 地址

    @property(Button)
    btn_wenhao: Button = null; // 说明

    @property(Node)
    masterSpr: Node = null; // 持有人标签

    @property(Node)
    bottomNode: Node = null; // 底部球杆节点


    @property(Node)
    scroll_buy: Node = null

    @property(Node)
    scroll_mine: Node = null

    @property(Prefab)
    cueItemPrefab: Prefab = null

    @property(SpriteFrame)
    cueFrames = []

    listData = null     // 球杆列表数据
    ownCuedata = null     // 我的球杆数据

    scrollContentH = 0  // 滚动视图的高度

    onLoad() {
        UtilTool.setScreen(this.node)
        this.node.getComponent(UITransform).setContentSize(view.getVisibleSize())

        UtilTool.setSize(this.scroll_mine, 3, [0, 2])
        UtilTool.setSize(this.scroll_mine.getChildByName("view"), 3, [0, 2])
        UtilTool.setSize(this.scroll_mine.getChildByName("view").getChildByName("content"), 3, [0, 2])
        UtilTool.setPos(find("empty_mine",this.scroll_mine), [0, 1], true)
        

        App.Event.on(EventConst.UPDATE_SET_NICK, this.setNickname, this)
        App.Event.on(EventConst.UPDATA_USERINFO, this.updateBtns, this)
        App.Event.on(EventConst.UPDATE_SET_HEAD, this.updateHead, this)
    }

    start() {

        this.setUI()

        // 地址
        this.label_address.string = PD.user.addressUrl

        this.setNickname()
        this.updateHead()
        this.reqListData() // 请求我的球杆

        let contentNode = find("view/content",this.scroll_mine)
        this.scrollContentH = contentNode.getComponent(UITransform).height
    }

    // 设置昵称
    setNickname() {
        if (PD.user.nickname=='' || PD.user.nickname==null){
            this.label_nick.string = App.language.getLanguageLab(181)
        }
        else {
            this.label_nick.string = UtilTool.getFormatNickname(PD.user.nickname, 16)
        }

        let nickBtn = find("contentNode/topNode/btn_nick",this.node)
        UtilTool.adaptiveLabel3([this.label_nick.node, nickBtn], -120, 0)
    }

    updateBtns(data) {
        let isHolder = data.isHolder === 1
        PD.setHolder(isHolder) // 设置球室持有人状态

        this.setUI()
    }

    // 更新头像
    updateHead() {
        let headDict = App.Scene.getHallRes("images/head")
        if (headDict["head_" + PD.user.headId]) {
            find("contentNode/topNode/com_head1",this.node).getComponent(Sprite).spriteFrame = headDict["head_" + PD.user.headId]
        }
    }

    setUI() {
        // 成为球室持有人按钮
        this.btn_become_master.node.active = !PD.playerInfo.isHolder
        // 收益明细按钮
        this.btn_income.node.active = PD.playerInfo.isHolder
        // 持有人标签
        this.masterSpr.active = PD.playerInfo.isHolder
        // 持有人说明
        this.btn_wenhao.node.active = PD.playerInfo.isHolder
    }

    // 成为球室持有人
    async onBtnBecomeMaster() {
        UtilTool.printLog("test onBtnBecomeMaster")

        this.playClickAudio()

        // 显示成为球室持有人确认界面
        let cb = (btnIndex)=>{
        }

        let node = await loadCommonPreFab('prefabs/hall/multiplay/BeMasterWnd', this.node)
        let beMasterCtrl = node.getComponent(BeMasterWnd)
        beMasterCtrl.initData(1, cb)
        return node

    }

    // 查看收益明细
    onBtnIncome() {
        this.playClickAudio()
        loadCommonPreFab('prefabs/hall/minePanel/incomeRecord', this.node)
    }

    // 修改昵称
    onBtnModifyNick() {
        this.playClickAudio()
        loadCommonPreFab('prefabs/hall/minePanel/setNick', this.node)
    }

    // 查看持有人说明
    async onBtnWenhao() {
        this.playClickAudio()
        
        let node = await loadCommonPreFab('prefabs/hall/multiplay/BeMasterWnd', this.node)
        let beMasterCtrl = node.getComponent(BeMasterWnd)
        beMasterCtrl.initData(2)
        return node

    }

    // 更换头像
    onBtnchangeHead() {
        this.playClickAudio()
        loadCommonPreFab('prefabs/hall/minePanel/changeHead', this.node)
    }

    protected onDestroy(): void {
        App.Event.off(EventConst.UPDATA_USERINFO, this.updateBtns, this)
        App.Event.off(EventConst.UPDATE_SET_NICK, this.setNickname, this)
        App.Event.off(EventConst.UPDATE_SET_HEAD,this.updateHead,this)
    }


    ///////////////////////////////////////////////////////////////////////// bottom /////////////////////////////////////////////////////////////////////////
    /**
     * 请求我的球杆列表
     */
    reqListData(pInit=true) {
        wsTool.send({msgCode:CommConst.Req_CUE_LIST, "status":1})
        .then((data) => {
            if(data.result == 0) {
                PD.user.currentCue = data.currentUseClub
                // 排序
                data.clubList.sort((club1, club2)=>{ // 降序,把正在使用的球杆放在第一位
                    return club2.status - club1.status
                })

                this.setMineCueInfo(data.clubList)
                this.listData = data
                this.ownCuedata = data.clubList

                this.refreshMineScroll()
                App.Event.emit(EventConst.UPDATE_CUE_DETAIL, data.clubList)
            } else {
                showErrorTip(data.result)
            }
        })
    }

    /** 
     * 刷新我的球杆界面
    */
    refreshMineScroll() {
        if (this.ownCuedata == null) {
            return
        }

        let contentNode = find("view/content",this.scroll_mine)
        contentNode.removeAllChildren()
        find("empty_mine",this.scroll_mine).active = this.ownCuedata.length<=0

        // 滚动视图设置
        let allH = this.ownCuedata.length * 520
        let H = contentNode.getComponent(UITransform).height
        if (H<allH){
            H = allH
        }
        contentNode.getComponent(UITransform).height = H
        this.scroll_mine.getComponent(ScrollView).scrollToTop()

        for (let index = 0; index < this.ownCuedata.length; index++) {
            let itemNode = instantiate(this.cueItemPrefab)
            itemNode.parent = contentNode

            let data = this.ownCuedata[index]
            let nameLabel = find("bg/nameLabel", itemNode).getComponent(Label)   // 名字
            let levelLabel = find("bg/levelLabel", itemNode).getComponent(Label) // 等级
            let cueSprite = find("bg/cueSprite", itemNode).getComponent(Sprite)  // 球杆图片
            let coinLabel = find("bg/coinLabel", itemNode)                       // 金币
            let coinSprite = find("bg/coinSprite", itemNode)                     // 金币图片

            let vigorLabel_v = find("bg/propertyNode/vigorLabel_v", itemNode).getComponent(Label)                     // 力度
            let sightLabel_v = find("bg/propertyNode/sightLabel_v", itemNode).getComponent(Label)                     // 瞄准
            let charmLabel_v = find("bg/propertyNode/charmLabel_v", itemNode).getComponent(Label)                     // 角度

            let btn_bg = find("bg", itemNode)                                   // 升级按钮
            let btn_buy = find("bg/btn_buy", itemNode)                          // 购买按钮
            let btn_own = find("bg/btn_own", itemNode)                          // 已拥有按钮
            let btn_upgrade = find("bg/btn_upgrade", itemNode)                  // 强化按钮
            let usingNode = find("bg/usingNode", itemNode)                      // 使用中

            nameLabel.string = App.language.getLanguageLab(176)[data.number + ""]
            cueSprite.spriteFrame = this.cueFrames[data.number]
            // coinLabel.getComponent(Label).string = data.gold + ""
            // UtilTool.adaptiveLabel3([coinLabel,coinSprite],-420,10)
            coinLabel.active = false
            coinSprite.active = false

            // 等级
            if (data.level==null) {
                levelLabel.node.active = false
            }
            else{
                levelLabel.string = "Lv." + data.level
            }

            // 球杆属性
            vigorLabel_v.string = data.vigor + ""
            sightLabel_v.string = data.sightLine + ""
            charmLabel_v.string = data.charm + ""

            // 按钮显示
            btn_buy.active = false
            btn_own.active = false
            btn_upgrade.active = true//data.number!=this.listData.currentUseClub
            usingNode.active = data.number==this.listData.currentUseClub

            // 强化按钮
            // App.onClick.removeButtonClickEvent(btn_upgrade.getComponent(Button),Node.EventType.TOUCH_END)
            App.onClick.addButtonClickEvent(btn_upgrade.getComponent(Button), async() =>{
                this.onBtnUpgrade(data)
            }, this,null,true,Node.EventType.TOUCH_END,null,500);

            // 使用按钮
            App.onClick.removeButtonClickEvent(btn_bg.getComponent(Button),Node.EventType.TOUCH_END)
            App.onClick.addButtonClickEvent(btn_bg.getComponent(Button), async() =>{
                if (data.number==this.listData.currentUseClub) return    // 重复选择
                
                this.clickUse(data)
            }, this,null,true,Node.EventType.TOUCH_END,null,500);
            
        } 
    }

    // 显示升级界面
    async onBtnUpgrade(data) {
        App.Audio.playOneShot("click")
        let node = await loadCommonPreFab("prefabs/hall/minePanel/upgradeCue", null)
        node.getComponent(UpgradeCuePanel).setData(this, data)
    }

    /**
     * 设置我的使用的球杆信息
     * @param clubList 
     */
    setMineCueInfo(clubList) {
        clubList.forEach(element => {
            if (element.status == 2) {
                PD.mineCueInfo.number = element.number
                PD.mineCueInfo.charm = element.charm
                PD.mineCueInfo.sightLine = element.sightLine
                PD.mineCueInfo.vigor = element.vigor
            }
        })
        
    }

    /**
     * 使用球杆
     * @param data 球杆数据
     */
    async clickUse(cueData) {
        App.Audio.playOneShot("click")
        
        wsTool.send({msgCode:CommConst.Req_USE_CUE, "number":cueData.number})
        .then((data) => {
            if(data.result == 0) {
                showTip(UtilTool.formatStr(App.language.getLanguageLab(177), App.language.getLanguageLab(176)[cueData.number + ""]))
                this.reqListData()

            } else {
                showErrorTip(data.result)
            }
        })
    }


}

